package com.yuke.cloud.service.wmc.controller.frontend;

import com.alibaba.fastjson.JSONObject;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.wmc.entity.WmsPrinter;
import com.yuke.cloud.service.wmc.entity.WmsWarehouse;
import com.yuke.cloud.service.wmc.entity.WmsWarehouseGroup;
import com.yuke.cloud.service.wmc.service.DicRegionService;
import com.yuke.cloud.service.wmc.service.WmsPrinterService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.service.wmc.service.WmsWarehouseGroupService;
import com.yuke.cloud.service.wmc.service.WmsWarehouseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import com.yuke.cloud.common.core.support.BaseController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wg on 2018/11/22.
 */
@Api(value = "WEB - WmsPrinterController", tags = "处理WmsPrinter相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/wms/printer")
@Slf4j
public class WmsPrinterController extends BaseController {
    @Resource
    private WmsPrinterService wmsPrinterService;
    @Resource
    private WmsWarehouseGroupService wmsWarehouseGroupService;
    @Resource
    private WmsWarehouseService wmsWarehouseService;
    @Resource
    private DicRegionService dicRegionService;


    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "wmsPrinter", value = "该数据记录的POJO") @RequestBody WmsPrinter wmsPrinter) {

        // add by wg 20190219 将打印机注册到快宝云服务上
        // 获取仓库信息
        // 打印机注册时的用户电话为可选，暂不从数据库获取
//        WmsWarehouseDto wmsWarehouse = wmsWarehouseService.findById(wmsPrinter.getWarehouseId());
//        if (wmsWarehouse != null && PublicUtil.isNotEmpty(wmsWarehouse.getMobile())) {
//            wmsPrinter.setMobileNo(wmsWarehouse.getMobile());
//        }else {
//            wmsPrinter.setMobileNo("18071540691");  // 设置成一个固定的联系电话
//        }

        wmsPrinter.setMobileNo("18071540691");  // 设置成一个固定的联系电话
        printMachineManager printManager = new printMachineManager();
        try{
            Wrapper ret = printManager.add(wmsPrinter);
            if (ret != null && ret.getCode() == 200) {
                JSONObject jsonObject0 = JSONObject.parseObject(ret.getResult().toString());
                JSONObject dateObject = JSONObject.parseObject(jsonObject0.getJSONObject("data").toString());
                if (dateObject != null && dateObject.get("status") != null && "success".equals(dateObject.get("status").toString())) {
                    String agentId = dateObject.get("agent_id").toString();
                    wmsPrinter.setAgentId(agentId);
                    wmsPrinterService.save(wmsPrinter);
                } else {
                    return WrapMapper.error("注册打印机失败");
                }
            } else {
                return WrapMapper.error("注册打印机失败");
            }
        } catch (Exception e){
            log.error("向云打印平台注册打印机失败，打印机名:{}, error={}", wmsPrinter.getPrinterName(), e.getMessage());
        }

        return WrapMapper.ok(wmsPrinter);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {

        WmsPrinter wmsPrinter = wmsPrinterService.findById(id); // add by wg 20190219 将注册到快宝云服务上的打印机删除掉

        wmsPrinterService.deleteById(id);

        // add by wg 20190219 将注册到快宝云服务上的打印机删除掉
        if (wmsPrinter != null && PublicUtil.isNotEmpty(wmsPrinter.getAuthCode())) {
            printMachineManager printManager = new printMachineManager();

            try{
                printManager.delete(wmsPrinter.getAuthCode());
            } catch (Exception e){
                log.error("向云打印平台删除打印机失败，打印机名:{}, error={}", wmsPrinter.getPrinterName(), e.getMessage());
            }
        }

        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "wmsPrinter", value = "需要修改的内容") @RequestBody WmsPrinter wmsPrinter) {
        wmsPrinterService.update(wmsPrinter);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<WmsPrinter> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        WmsPrinter wmsPrinter = wmsPrinterService.findById(id);
        return WrapMapper.ok(wmsPrinter);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<WmsPrinter>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                              @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<Map> list = wmsPrinterService.findallit();
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    @GetMapping("/warehouse/{id}")
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<WmsPrinter>> list2(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                               @ApiParam(name = "id", value = "记录id") @PathVariable Long id,
                                               @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<Map> list = wmsPrinterService.findAllbywarehouseid(id);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    @GetMapping("/findwarehouseid/{id}")
    @ApiOperation(httpMethod = "GET", value = "通过组织id获取仓库id")
    public Wrapper list3(@ApiParam(name = "id", value = "组织id") @PathVariable Long id) {
        WmsWarehouseGroup wmsWarehouseGroup = new WmsWarehouseGroup();
        wmsWarehouseGroup.setGroupId(id);
        List<Map> list = new ArrayList<>();
        List<WmsWarehouseGroup> select = wmsWarehouseGroupService.select(wmsWarehouseGroup);
        for (WmsWarehouseGroup wms : select) {
            Map map = new HashMap();
            Long warehouseId = wms.getWarehouseId();
            map.put("warehouseid", warehouseId);
            WmsWarehouse byId = wmsWarehouseService.findById(warehouseId);
            if (byId != null) {
                map.put("name", byId.getWarehouseName());
            }
            list.add(map);
        }

        return WrapMapper.ok(list);
    }


    @PostMapping("/batchdelete")
    public Wrapper batchdelete(@RequestBody List<Long> ids) {

        Example example = new Example(WmsPrinter.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("printerId", ids);
        List<WmsPrinter> wmsPrinterList = wmsPrinterService.selectByExample(example); // add by wg 20190219 将注册到快宝云服务上的打印机删除掉

        wmsPrinterService.beathdelete(ids);

        // add by wg 20190219 将注册到快宝云服务上的打印机删除掉
        if (wmsPrinterList != null) {
            printMachineManager printManager = new printMachineManager();
            for (WmsPrinter wmsPrinter:wmsPrinterList) {
                if (wmsPrinter != null && PublicUtil.isNotEmpty(wmsPrinter.getAuthCode())) {
                    try{
                        printManager.delete(wmsPrinter.getAuthCode());
                    } catch (Exception e){
                        log.error("向云打印平台删除打印机失败，打印机名:{}, error={}", wmsPrinter.getPrinterName(), e.getMessage());
                    }
                }
            }
        }

        return WrapMapper.ok("success");
    }

    //todo 通过仓库名字获取打印机，打印机名字唯一性确认
    @GetMapping("/getprinterbywarehousename")
    public Wrapper<PageInfo<WmsPrinter>> getprinterbywarehousename(@ApiParam(name = "name", value = "组织id") @RequestParam("name") String name,
                                                                   @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                                   @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<Map> list = wmsPrinterService.getprintbyname(name);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);


    }

    @GetMapping("/ifunique")
    public Wrapper ifunique(@ApiParam(name = "name", value = "组织id") @Param("name") String name,
                            @ApiParam(name = "warehouseId", value = "组织id") @Param("warehouseId") Long warehouseId
    ) {
        Example example = new Example(WmsPrinter.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("printerName", name);
        if (warehouseId != null) {
            criteria.andNotEqualTo("warehouseId", warehouseId);
        }
        List<WmsPrinter> select = wmsPrinterService.selectByExample(example);
        if (select.size() >= 1) {
            return WrapMapper.ok("no");
        } else {
            return WrapMapper.ok("yes");
        }

    }

    public static void main(String[] args) throws Exception {

        WmsPrinter wmsPrinter = new WmsPrinter();
        wmsPrinter.setPrinterName("test");
        wmsPrinter.setAuthCode("9676647413644282");
        wmsPrinter.setWarehouseId(123213L);
        wmsPrinter.setMobileNo("3213213");

        Wrapper ret = new WmsPrinterController().add(wmsPrinter);
        System.out.println(ret);
    }

}
